var calendarManageList = function(targetObj){
	this.sysUtils = new kendoUtils();
	this.targetObj = targetObj;
	this.getLunarCalendar  = new GetLunarCalendar();
	this.monthUpperCase = ["一","二","三","四","五","六","七","八","九","十","十一","十二"];
	this.init();
	return this;
};

calendarManageList.prototype={
		init:function(){
			var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj.find("#calendarDiv"));
			var bindFunctionArray = [{fName:"saveCalendarInfo",fs:this.saveCalendarInfo}];
			this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
			this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
			//绑定月份点击事件
			var monthUL = this.targetObj.find("#monthUL");
			for(var i = 1 ;i<=12;i++){
				var li = $("<li><a href='#'>" + i + "</a></li>")
				li.data("month",i);
				li.bind("click",{that:this,type:"month"},this.monthClick);
				monthUL.append(li);
			}
			//生成年份下拉列表框
			var yearSelect = this.targetObj.find("#calendar_select");
			var date = new Date();
			var year = date.getFullYear();
			for(var i = 0; i < 10 ;i++){
				var option = $("<option>" + (year + i) + "</option>");
				option.data("year",(year + i));
				yearSelect.append(option);
			}
			yearSelect.bind("change",this,function(e){
				e.data.findCalendarByYear(false);
			});
			//生成切换系统下拉列表框
			this.createSystemDropDownList();
		},
		createSystemDropDownList:function(){
			var that = this;
			that.changeFlag = false;
			JsonpAjax(baseApiPath + "systemManage/findSystemListByCalendar",null,"json",function(result){
				that.targetObj.find("#systemDropDown").kendoDropDownList({
					dataSource:result,
					dataTextField: "systemName",
					dataValueField: "id",
					minLength: 3,
					dataBound:function(){
						if(result.length > 0){
							that.sysUtils.mvvmModel.set("systemID",result[0]["id"]);
						}
					},
					change:function(e){
						that.changeFlag = true;
						that.findCalendarByYear(false);  //重新加载系统缓存日历
					}
				});
				that.findCalendarByYear(true);
			});
			var calType = this.targetObj.find("#calType");
			var flagEn = this.targetObj.find("#flagEn");
			var dayFlag = this.targetObj.find("#dayFlag");
			var stop = Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_STOP,Utils.systemType.SYS);
			Utils.createDataDictDropDownList([{div:calType,parentModelKey:BASIS.CAL_TYPE.ROOT},
			                                  {div:flagEn,parentModelKey:BASIS.DATA_STATUS.ROOT,select:stop},
			                                  {div:dayFlag,parentModelKey:BASIS.DATA_STATUS.ROOT,select:stop,change:this.dayFlagFunction}],this,Utils.systemType.SYS);
		},
		/**
		 * 整天非整天模式切换
		 */
		dayFlagFunction:function(e){
			var value = "";
			if(e.constructor == Object){
				value = parseInt(this.value());
			}else{
				value = e;
			}
			//不启用非整天模式
			var dayFlagFlase = Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_STOP,Utils.systemType.SYS);
			var timePicker = calendarList.targetObj.find("#calendarDiv").find("div[timeDiv]");
			if(value == dayFlagFlase){   //整天模式
				timePicker.css("display","none");
				calendarList.sysUtils.setBindFieldNull([{fieldName:"beginTime"},{fieldName:"endTime"}]);
			}else{    //非整天模式
				timePicker.css("display","block");
				calendarList.sysUtils.setBindFieldValue({beginTime:"08:00:00",endTime:"18:00:00"});
			}
		},
		/**
		 * 查询对应系统某一年的所有日历数据
		 */
		findCalendarByYear:function(isLoad){
			var year = parseInt(this.targetObj.find("#calendar_select").val());
			var systemDropDown = this.targetObj.find("#systemDropDown").data("kendoDropDownList");
			var systemID = systemDropDown.value();
			var that = this;
			JsonpAjax(baseApiPath + "calendarManage/findCalendarInfoList?year="+year+"&systemID="+systemID,"","json",function(result){
				//把List转换成Map存储
				that.calendarInfoMap = new Map();
				for(var i = 0;i<result.length;i++){
					//key为年、月、日
					that.calendarInfoMap.put(result[i]["calTime"].substring(0,10),result[i]);
				}
				var monthUL = that.targetObj.find("#monthUL");
				if(isLoad){      //首次加载的时候模拟点击一月
					//模拟点击一月份
					monthUL.find("li:first").trigger("click");
				}else{   //年份切换和系统切换时模拟点击当前选中
					monthUL.find("a[style]").trigger("click");
				}
			});
		},
		/**
		 * 点击月份展示每月天数并且显示在对应的星期单元格中
		 */
		monthClick:function(target){
			var month = 0;
			var year = 0;
			var that =  target.data["that"];
			var monthUL = that.targetObj.find("#monthUL");
			if(target.data["type"] == "month"){
				month = $(target.target).parent("li").data("month");
				//如果选择的是当月,并且没有切换系统则不做任何操作
				if(null != that.currDate && (that.currDate.getMonth() + 1  == month) && that.changeFlag == false){
					return;
				}
				if(that.changeFlag == true){   //如果切换系统了，执行一次操作，把changeFlag标志改变
					that.changeFlag = false;
				}
				monthUL.find("a[style]").removeAttr("style");
				if(null == month){
					month = $(target.target).data("month");
					$(target.target).find("a").css({background:"#87ccfc",color:"#0e60ab"});
				}else{
					//为选中的月份添加显示样式
					$(target.target).css({background:"#87ccfc",color:"#0e60ab"});
				}
				year = parseInt(that.targetObj.find("#calendar_select").val());
				var upperCase = that.monthUpperCase[month - 1];
				that.targetObj.find(".calendar_left_01").html(upperCase + "月");
			}else{   //选择的是年，选择年时需要重新查询数据库缓存数据
				year = parseInt($(target.target).val());
				month = monthUL.find("a[style]").parent("li").data("month");
			}
			//重置右边属性设置
//			var stop = Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_STOP);
			var calendarInfo = {calTime:"",calType:"",dayFlag:"",flagEn:"",beginTime:"",endTime:""}
			that.sysUtils.setBindFieldValue(calendarInfo,true);
			var date = new Date(year,month,0);
			that.currDate = date; //存储时间
			var dayCont = date.getDate();   //当前月份的最后一天
			var weekDay = new Date(year,month - 1 ,1).getDay();
			//填充日期
			var dayDivList = that.targetObj.find("#calendarMiddleUL");
			dayDivList.empty();
			var day = 1;
			var HOLIDAY_SEASON = Utils.getModelValueByModelKey(BASIS.CAL_TYPE.CAL_TYPE_HOLIDAY_SEASON,Utils.systemType.SYS);
			for(var i = 0;i<42;i++){
				var li = $("<li><a href='#'></a></li>")
				if(i < (dayCont + weekDay) && i >= weekDay){
					var currDate = new Date(year,month - 1 , day);
					var cal = that.getLunarCalendar.showCal(currDate);
					li.attr("day",day);
					li.find("a").append("<p>" + (day++) + "</p>" + cal);
					//判断如果是周六周日则增加为节假日的标志
					var currDay = currDate.getDay();
					li.data("isHoliday",false);
					//从缓存中拉取数据看是否节假日还是工作日
					var calendarInfo = that.calendarInfoMap.get(currDate.pattern("yyyy-MM-dd"))
					if(((currDay == 0 || currDay == 6) && (null == calendarInfo || calendarInfo["calType"] == HOLIDAY_SEASON)) || 
							(null != calendarInfo && calendarInfo["calType"] == HOLIDAY_SEASON)){
						li.find("a").css({"background-color":"#ffe3e3","background-image":"url(images/calendar_bg03.png)",
							"background-repeat":"no-repeat","textDecoration":"none"});
						li.find("p").css({"color":"#b9262c","textDecoration":"none"});
						li.data("isHoliday",true);
					}
					li.bind("click",that,that.dayLiClick);
				}else{
					li.find("a").css({"background":"#EEEEEE"});
				}
				dayDivList.append(li);
			}
		},
		/**
		 * 单击日历中每天的单元格
		 * @param e
		 */
		dayLiClick:function(e){
			var that = e.data;
			var isHoliday = $(e.target).parents("li").data("isHoliday")
			var day = $(e.target).parents("li").attr("day");
			if(isHoliday == null){
				isHoliday = $(e.target).data("isHoliday");
				day = $(e.target).attr("day");
			}
			var calTypeStr = "";
			if(isHoliday){
				calTypeStr = Utils.getModelValueByModelKey(BASIS.CAL_TYPE.CAL_TYPE_HOLIDAY_SEASON,Utils.systemType.SYS);
			}else{
				calTypeStr = Utils.getModelValueByModelKey(BASIS.CAL_TYPE.CAL_TYPE_WORKING_DAYS,Utils.systemType.SYS);
			}
			that.currDate.setDate(parseInt(day));
			var calendarInfo = that.calendarInfoMap.get(that.currDate.pattern("yyyy-MM-dd"))
			if(null == calendarInfo){
				var stop = Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_STOP,Utils.systemType.SYS);
				calendarInfo = {calTime:that.currDate.pattern("yyyy-MM-dd"),calType:calTypeStr,dayFlag:stop,flagEn:stop}
			}else{
				calendarInfo["calTime"] = that.currDate.pattern("yyyy-MM-dd");
				calendarInfo["beginTime"] = calendarInfo["beginTimeStr"];
				calendarInfo["endTime"] = calendarInfo["endTimeStr"];
			}
			that.sysUtils.setBindFieldValue(calendarInfo);
			//触发整天方法
			that.dayFlagFunction(calendarInfo["dayFlag"]);
		},
		/**
		 * 保存设置的日历信息
		 * @param e
		 */
		saveCalendarInfo:function(e){
			var that =  $(e.target).data("that");
			var basCalendarInfo = that.sysUtils.getBindDocJson();
			if(undefined == basCalendarInfo["calTime"]){
				return notification({ title:"提示信息",message:"日历日期不能为空!!"},'info');
			}
			if(undefined == basCalendarInfo["calType"]){
				return notification({ title:"提示信息",message:"请选择日历类型!!"},'info');
			}
			if(undefined == basCalendarInfo["flagEn"]){
				return notification({ title:"提示信息",message:"请选择是否启用公共日历!!"},'info');
			}
			if(undefined == basCalendarInfo["dayFlag"]){
				return notification({ title:"提示信息",message:"请选择是否启用非整天模式!!"},'info');
			}
			var dayFlagTrue = Utils.getModelValueByModelKey(BASIS.DATA_STATUS.DATA_STATUS_START,Utils.systemType.SYS);
			var currYearMonth = that.currDate.pattern("yyyy-MM-dd");
			if(basCalendarInfo["dayFlag"] == dayFlagTrue){   //如果启用非整天模式，则校验开始时间和结束时间是否有冲突
				if(undefined == basCalendarInfo["beginTime"]){
					return notification({ title:"提示信息",message:"请选择开始时间!!"},'info');
				}
				if(undefined == basCalendarInfo["endTime"]){
					return notification({ title:"提示信息",message:"请选择结束时间!!"},'info');
				}
				if(basCalendarInfo["beginTime"].constructor == String){  //如果为String要转换成date
					basCalendarInfo["beginTime"] = new Date(currYearMonth + " " + basCalendarInfo["beginTime"]);
				}
				if(basCalendarInfo["endTime"].constructor == String){  //如果为String要转换成date
					basCalendarInfo["endTime"] = new Date(currYearMonth + " " + basCalendarInfo["endTime"]);
				}
				var bgHours = basCalendarInfo["beginTime"].getHours();
				var endHours = basCalendarInfo["endTime"].getHours();
				var bgMinutes = basCalendarInfo["beginTime"].getMinutes();
				var endMinutes = basCalendarInfo["endTime"].getMinutes();
				if(bgHours > endHours || (bgHours <= endHours && bgMinutes > endMinutes)){
					return notification({ title:"提示信息",message:"开始时间不能大于结束时间!!"},'info');
				}
			}
			var calendarInfo = that.calendarInfoMap.get(currYearMonth)
			if(null != calendarInfo){  //如果存在缓存对象则是更新，把一些数据赋值给到保存对象
				basCalendarInfo["id"] = calendarInfo["id"];
				basCalendarInfo["createBy"]   = calendarInfo["createBy"];
				basCalendarInfo["createTime"] = calendarInfo["createTime"];
			}
			JsonpAjax(baseApiPath + "calendarManage/saveOrUpdate",JSON.stringify(basCalendarInfo),"json",function(result){
				if(isNotEmpt(result["expStr"])){   //存在异常信息时提示用户
					that.calendarInfoMap.remove(currYearMonth);
					notification({ title:"提示信息",message:result["expStr"]},'info');
				}else{
					that.calendarInfoMap.put(currYearMonth,result);
				}
				//操作成功后，修改界面显示
				var date = that.currDate.getDate();
				var li = that.targetObj.find("#calendarMiddleUL").find("li[day="+date+"]");
				var WORKING_DAY = Utils.getModelValueByModelKey(BASIS.CAL_TYPE.CAL_TYPE_WORKING_DAYS,Utils.systemType.SYS);
				if(result["calType"] == WORKING_DAY){
					li.find("a").removeAttr("style");
					li.find("p").removeAttr("style");
					li.data("isHoliday",false);
				}else{
					li.find("a").css({"background-color":"#ffe3e3","background-image":"url(images/calendar_bg03.png)",
						"background-repeat":"no-repeat","textDecoration":"none"});
					li.find("p").css({"color":"#b9262c","textDecoration":"none"});
					li.data("isHoliday",true);
				}
			});
		}
};



var GetLunarCalendar = function(){
	//定义全局变量 
	this.CalendarData=new Array(100); 
	this.madd=[0,31,59,90,120,151,181,212,243,273,304,334]; 
	this.tgString="甲乙丙丁戊己庚辛壬癸"; 
	this.dzString="子丑寅卯辰巳午未申酉戌亥"; 
	this.numString="一二三四五六七八九十"; 
	this.monString="正二三四五六七八九十冬腊"; 
	this.weekString="日一二三四五六"; 
	this.sx="鼠牛虎兔龙蛇马羊猴鸡狗猪"; 
	this.cYear,this.cMonth,this.cDay,this.TheDate; 
	this.CalendarData = new Array(0xA4B,0x5164B,0x6A5,0x6D4,0x415B5,0x2B6,0x957,0x2092F,0x497,0x60C96,0xD4A,0xEA5,0x50DA9,0x5AD,0x2B6,0x3126E, 0x92E,0x7192D,0xC95,0xD4A,0x61B4A,0xB55,0x56A,0x4155B, 0x25D,0x92D,0x2192B,0xA95,0x71695,0x6CA,0xB55,0x50AB5,0x4DA,0xA5B,0x30A57,0x52B,0x8152A,0xE95,0x6AA,0x615AA,0xAB5,0x4B6,0x414AE,0xA57,0x526,0x31D26,0xD95,0x70B55,0x56A,0x96D,0x5095D,0x4AD,0xA4D,0x41A4D,0xD25,0x81AA5,0xB54,0xB6A,0x612DA,0x95B,0x49B,0x41497,0xA4B,0xA164B, 0x6A5,0x6D4,0x615B4,0xAB6,0x957,0x5092F,0x497,0x64B, 0x30D4A,0xEA5,0x80D65,0x5AC,0xAB6,0x5126D,0x92E,0xC96,0x41A95,0xD4A,0xDA5,0x20B55,0x56A,0x7155B,0x25D,0x92D,0x5192B,0xA95,0xB4A,0x416AA,0xAD5,0x90AB5,0x4BA,0xA5B, 0x60A57,0x52B,0xA93,0x40E95); 
	return this;
};
GetLunarCalendar.prototype={
		/*获取当前农历*/
		showCal:function(D){
			var yy=D.getFullYear(); 
			var mm=D.getMonth()+1; 
			var dd=D.getDate(); 
			var ww=D.getDay(); 
			var ss=parseInt(D.getTime() / 1000); 
			if (yy<100) yy="19"+yy; 
			return this.GetLunarDay(yy,mm,dd); 
		},
		GetLunarDay:function(solarYear,solarMonth,solarDay){ 
			if(solarYear<1921 || solarYear>2020){ 
				return ""; 
			}else{ 
				solarMonth = (parseInt(solarMonth)>0) ? (solarMonth-1) : 11; 
				this.e2c(solarYear,solarMonth,solarDay); 
				return this.GetcDateString(); 
			} 
		},
		//农历转换 
		e2c : function (){ 
			this.TheDate= (arguments.length!=3) ? new Date() : new Date(arguments[0],arguments[1],arguments[2]); 
			var total,m,n,k; 
			var isEnd=false; 
			var tmp=this.TheDate.getYear(); 
			if(tmp<1900){ 
				tmp+=1900; 
			} 
			total=(tmp-1921)*365+Math.floor((tmp-1921)/4)+this.madd[this.TheDate.getMonth()]+this.TheDate.getDate()-38; 
			 
			if(this.TheDate.getYear()%4==0&&this.TheDate.getMonth()>1) { 
				total++; 
			} 
			for(m=0;;m++){
				k=(this.CalendarData[m]<0xfff)?11:12; 
				for(n=k;n>=0;n--){ 
					if(total<=29+this.GetBit(this.CalendarData[m],n)){ 
						isEnd=true; break; 
					} 
					total=total-29-this.GetBit(this.CalendarData[m],n); 
				} 
				if(isEnd) break; 
			} 
			this.cYear=1921 + m; 
			this.cMonth=k-n+1; 
			this.cDay=total; 
			if(k==12){ 
				if(this.cMonth==Math.floor(this.CalendarData[m]/0x10000)+1){ 
					this.cMonth=1-this.cMonth; 
				} 
				if(this.cMonth>Math.floor(this.CalendarData[m]/0x10000)+1){ 
					this.cMonth--; 
				} 
			} 
		},
		GetBit:function (m,n){ 
			return (m>>n)&1; 
		},
		GetcDateString : function (){ 
			/*显示农历年：（ 如：甲午(马)年 ）*/
			var tepMonth = "";
			if(this.cMonth<1){ 
				tepMonth+="(闰)"; 
				tepMonth+=this.monString.charAt(-this.cMonth-1); 
			}else{ 
				tepMonth+=this.monString.charAt(this.cMonth-1); 
			} 
			tepMonth+="月"; 
			var tmp=""; 
			tmp+=(this.cDay<11)?"初":((this.cDay<20)?"十":((this.cDay<30)?"廿":"三十")); 
			if (this.cDay%10!=0||this.cDay==10){ 
				tmp+=this.numString.charAt((this.cDay-1)%10); 
			} 
			var returnHtml = "";
			var color = "#228dce";
			var jq = this.SolarTerm(this.TheDate);
			if(jq != null){
				returnHtml = jq;
			}else if(tmp == "初一" && tepMonth == "正月"){
				returnHtml = "春节";
			}else if(tmp == "初一"){
				returnHtml = tepMonth;
				color = "#b1afaf";
			}else{
				returnHtml = tmp;
				color = "#b1afaf";
			}
			return "<span style='font-size:20px;color:"+color+"'>"+returnHtml+"</span>";
		},
		SolarTerm : function(DateGL){
			var SolarTermStr=new Array(
					"小寒","大寒","立春","雨水","惊蛰","春分",
					"清明","谷雨","立夏","小满","芒种","夏至",
					"小暑","大暑","立秋","处暑","白露","秋分",
					"寒露","霜降","立冬","小雪","大雪","冬至");
			var DifferenceInMonth=new Array(
					1272060,1275495,1281180,1289445,1299225,1310355,
					1321560,1333035,1342770,1350855,1356420,1359045,
					1358580,1355055,1348695,1340040,1329630,1318455,
					1306935,1297380,1286865,1277730,1274550,1271556);

			var DifferenceInYear=31556926;
			var BeginTime=new Date(1901/1/1);

			BeginTime.setTime(947120460000);
			for(;DateGL.getFullYear()<BeginTime.getFullYear();){
				BeginTime.setTime(BeginTime.getTime()-DifferenceInYear*1000);
			}
			for(;DateGL.getFullYear()>BeginTime.getFullYear();){
				BeginTime.setTime(BeginTime.getTime()+DifferenceInYear*1000);
			}
			for(var M=0;DateGL.getMonth()>BeginTime.getMonth();M++){
				BeginTime.setTime(BeginTime.getTime()+DifferenceInMonth[M]*1000);
			}
			if(DateGL.getDate()>BeginTime.getDate()){
				BeginTime.setTime(BeginTime.getTime()+DifferenceInMonth[M]*1000);
				M++;
			}
			if(DateGL.getDate()>BeginTime.getDate()){
				BeginTime.setTime(BeginTime.getTime()+DifferenceInMonth[M]*1000);
				M==23?M=0:M++;
			}
			BeginTime.setHours(0);    //设置为0时0分0秒
			BeginTime.setSeconds(0);
			BeginTime.setMinutes(0);
			if(DateGL.getTime() == BeginTime.getTime()){
				return SolarTermStr[M];
			}else{
				return null;
			}
		}
}